package blog.common.utils;


import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

@Slf4j
public class Redis {

    private StringRedisTemplate redisTemplate;

    private static final String PREFIX = "user";

    private static final String SPLIT = ":";

    private static final String DEFAULT_PRFIX = "DEFAULT";


    public Redis(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }


    public String get(String key) {
        try {
            return key == null ? null : redisTemplate.opsForValue().get(key);
        }catch (Exception e) {
            log.error("getredis is error,key:{}",key);
            return null;
        }
    }

    public boolean hasKey(String key) {
        try {
            return key == null ? false : redisTemplate.hasKey(key);
        }catch (Exception e) {
            log.error("hasKey is error,key:{}",key);
            return false;
        }
    }

    public boolean set(String key,String value) {
        try{
            if (key == null || value == null) {
                log.error("setredis is empty,key:{}",key);
                throw new Exception();
            }
            redisTemplate.opsForValue().set(key,value);
            return true;
        }catch (Exception e) {
            log.error("setredis is error,key:{}",key);
            return false;
        }
    }

    public boolean set(String key,String value,long timeout) {
        try{
            if (key == null || value == null || timeout <= 0) {
                log.error("setredis is errorset,key:{}",key);
                throw new Exception();
            }
            redisTemplate.opsForValue().set(key,value,timeout, TimeUnit.SECONDS);
            return true;
        }catch (Exception e) {
            log.error("setredis is error,key:{}",key);
            return false;
        }
    }

    public String bulidKey(String prefix,String... args) {
        if (prefix == null) {
            prefix = DEFAULT_PRFIX;
        }
        StringBuilder key = new StringBuilder();
        key.append(prefix);
        if (args != null) {
            for (String arg : args) {
                key.append(SPLIT).append(arg);
            }
        }
        return key.toString();
    }
}
